package sg.nus.iss.vmcs.utils;

import java.io.FileInputStream;
import java.util.Properties;

/**
 * Environment class for loading of utilities from the files<br><br>
 * Modifications:
 * <li>1/1/2011 - Philip - Converted this to a Singleton Class. Users should not depend on the init method</li>
 * <br><br>
 * @author Pang Pingli
 */
public class Environment {
	
	public final static String PROP_FILE 				= "data/propFile.txt";
	public final static String DRINK_PROP_FILE 			= "drinkFile";
	public final static String CASH_PROP_FILE 			= "cashFile";
	public final static String COIN_REGISTRY_PROP_FILE 	= "coinRegistryFile";
	public final static String PASSWORD 				= "password";
	public final static String DATA_PATH 				= "datapath";

	public Properties prop;
	
	/**
	 * Private Constructor that creates a Singleton Environment Instance
	 */
	private Environment() {}
	
	/**
	 * Static method that returns Singleton instance of Environment
	 * @return
	 */
	public static Environment getInstance() {
		Environment env = EnvironmentHolder.getEnvironment();
		env.initialize();
		
		return env;
	}
	
	/**
	 * Gets the password from the property file
	 * @return String containing the configured password
	 */
	public String getPassword(){
		return prop.getProperty(PASSWORD);
	}
	
	/**
	 * Gets the Drink Property File Location
	 * @return String containing location
	 */
	public String getDrinkPropFile(){
		return getDataPath() + prop.getProperty(DRINK_PROP_FILE);
	}

	/**
	 * Gets the Cash Property File Location
	 * @return String containing location
	 */
	public String getCashPropFile(){
		return getDataPath() + prop.getProperty(CASH_PROP_FILE);
	}
	
	/**
	 * Gets the Coin Registry Property File Location
	 * @return String containing location
	 */
	public String getCoinRegistryFile(){
		return getDataPath() + prop.getProperty(COIN_REGISTRY_PROP_FILE);
	}
	
	/**
	 * Initializes the Environment class
	 */
	private void initialize() {
		
		//Initialize properties first
		prop = new Properties();
		
		try {
			FileInputStream stream = new FileInputStream(PROP_FILE);
			prop.load(stream);
			stream.close();
		}
		catch (Exception e) {
            System.out.println("Error loading environment properties: " + e);
        }
	}
	
	/**
	 * Gets the data folder path for the project
	 * @return String containing the data folder path
	 */
	private String getDataPath() {
		return prop.getProperty(DATA_PATH);
	}
	
	/**
	 * Static inner class handling initialization of Environment. 
	 * This prevents synchronization issues
	 */
	private static class EnvironmentHolder {
		private static Environment instance = null;
		
		public static Environment getEnvironment() {
			if(instance  == null) {
				instance = new Environment();
			}
			
			return instance;
		}
	}
}